<!-- src/views/Login.vue -->
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../store/auth'
import { ElMessage } from 'element-plus'
import { authApi } from '../api/auth'
import apiClient from '../api'

const router = useRouter()
const authStore = useAuthStore()

const loginForm = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度至少3位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
}

const loading = ref(false)
const loginFormRef = ref()

// 在组件挂载时清除现有的认证信息
onMounted(() => {
  // 清除所有认证相关的信息
  localStorage.removeItem('token')
  localStorage.removeItem('userRole')
  // 清除axios默认头部的Authorization
  delete apiClient.defaults.headers.common['Authorization']
})

// 定义登录表单提交方法
const submitForm = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 注意：这里需要正确处理响应数据
        const response = await authApi.login({
          username: loginForm.username,
          password: loginForm.password
        })

        // 检查响应结构，根据实际API响应调整
        if (response && response.data) {
          // 从响应中提取token和用户信息
          const { token, user } = response.data

          if (token && user) {
            // 存储token和用户角色
            localStorage.setItem('token', token)
            localStorage.setItem('userRole', user.role)

            // 设置axios默认头部
            apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`

            // 登录成功后根据角色跳转
            if (user.role === 'ADMIN') {
              router.push('/admin')
            } else if (user.role === 'STUDENT') {
              try {
                // 使用原始的API调用来检查学生信息是否完善
                await apiClient.get('/student/profile')
                router.push('/student')
              } catch (error) {
                // 如果返回400错误，说明信息未完善
                if (error.response?.status === 400) {
                  router.push('/student/profile-setup')
                } else {
                  router.push('/student')
                }
              }
            }  else if (user.role === 'TEACHER') {
              try {
                // 检查教师信息是否完善
                await apiClient.get('/teacher/profile')
                router.push('/teacher')
              } catch (error) {
                // 如果返回400错误，说明信息未完善
                if (error.response?.status === 400) {
                  router.push('/teacher/profile-setup')
                } else {
                  router.push('/teacher')
                }
              }
            } else if (user.role === 'COMPANY') {
              router.push('/company')
            }

            ElMessage.success('登录成功')
          } else {
            ElMessage.error('登录响应格式错误')
          }
        } else {
          ElMessage.error(response?.message || '登录失败')
        }
      } catch (error) {
        console.error('登录错误:', error)
        ElMessage.error(error.response?.data?.message || '登录失败，请检查用户名和密码')
      } finally {
        loading.value = false
      }
    }
  })
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login-container">
    <div class="login-background">
      <div class="background-shapes">
        <div class="shape shape-1"></div>
        <div class="shape shape-2"></div>
        <div class="shape shape-3"></div>
      </div>
    </div>

    <div class="login-content">
      <!-- 左侧信息区 -->
      <div class="info-section">
        <h1>大学生专业实习管理系统</h1>
        <h2>欢迎登录</h2>
        <p>连接学生、教师与企业的一站式实习管理平台</p>
        <div class="features">
          <div class="feature">实习过程管理</div>
          <div class="feature">多方协同工作</div>
          <div class="feature">在线报告提交</div>
        </div>
      </div>

      <!-- 右侧登录区 -->
      <div class="form-section">
        <el-card class="login-card">
          <h3>用户登录</h3>
          <p class="form-subtitle">请输入您的账号信息</p>

          <el-form
              :model="loginForm"
              :rules="rules"
              ref="loginFormRef"
              @submit.native.prevent="submitForm"
          >
            <el-form-item prop="username">
              <el-input
                  v-model="loginForm.username"
                  placeholder="请输入用户名"
                  prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="请输入密码"
                  prefix-icon="Lock"
                  show-password
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                native-type="submit"
                class="login-btn"
                :loading="loading"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>

          <div class="form-footer">
            <span>还没有账号？<a @click="goToRegister">立即注册</a></span>
            <a class="forgot-link">忘记密码？</a>
          </div>
        </el-card>

        <div class="copyright">
          专业实习管理平台 ©2025
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
}

.login-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.background-shapes {
  position: relative;
  width: 100%;
  height: 100%;
}

.shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.shape-1 {
  width: 200px;
  height: 200px;
  top: -50px;
  right: -50px;
}

.shape-2 {
  width: 150px;
  height: 150px;
  bottom: 100px;
  left: -50px;
}

.shape-3 {
  width: 100px;
  height: 100px;
  bottom: -30px;
  right: 30%;
}

.login-content {
  position: relative;
  display: flex;
  width: 100%;
  height: 100%;
  max-width: 1200px;
  margin: 0 auto;
  align-items: center;
  justify-content: space-between;
  padding: 0 40px;
  z-index: 1;
}

@media (max-width: 768px) {
  .info-section{
    display: none;
  }
  .form-section{
    flex: 0 0 auto;
  }
  .login-content{
    justify-content: center;
  }
}

.info-section {
  flex: 1;
  color: white;
  max-width: 500px;
}

.info-section h1 {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 1rem;
  line-height: 1.2;
}

.info-section h2 {
  font-size: 1.8rem;
  font-weight: 400;
  margin-bottom: 1.5rem;
  opacity: 0.9;
}

.info-section p {
  font-size: 1.1rem;
  margin-bottom: 2.5rem;
  opacity: 0.8;
  line-height: 1.6;
}

.features {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.feature {
  padding: 12px 20px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  font-size: 1rem;
}

.form-section {
  flex: 0 0 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: transparent;
}

.login-card {
  width: 100%;
  padding: 40px 30px;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.login-card h3 {
  text-align: center;
  color: #2c3e50;
  font-size: 1.5rem;
  margin-bottom: 8px;
  font-weight: 600;
}

.form-subtitle {
  text-align: center;
  color: #7f8c8d;
  margin-bottom: 30px;
  font-size: 0.9rem;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  height: 48px;
}

.login-btn {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.login-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.form-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  font-size: 0.9rem;
  color: #7f8c8d;
}

.form-footer a {
  color: #667eea;
  cursor: pointer;
  text-decoration: none;
}

.forgot-link {
  color: #667eea !important;
}

.copyright {
  margin-top: 30px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 0.9rem;
  text-align: center;
}
</style>
